import { useState, useEffect, Fragment } from 'react'
import { useLocation, useParams, useNavigate } from 'react-router-dom'
import { Button } from 'antd'
import axios from 'utils/request'
import qs from 'qs'
import { useAppDispatch, useAppSelector } from 'store/hooks'
import { set_collect_arr } from '../classify/classifySlice'
import { ImageView } from 'components'
import './detail.scss'

interface DetailItemProps {
  classifyType: string
  collect: boolean
  count: number
  desc: string
  id: string
  img: string
  price: number
  title: string
}

const Detail = () => {
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  const store = useAppSelector((s) => s.classify)
  const [detailItem, setDetailItem] = useState<any>({})
  const [flag, setFlag] = useState(false)
  const location = useLocation()
  const params = useParams()

  const { tab, tabIndex } = qs.parse(location.search.replace(/\?/, ''))

  useEffect(() => {
    const fetchDetail = async () => {
      const detailData = await axios.get('/api/detail', { params: { tab, tabIndex, id: params.id } })
      // console.log('detailData', detailData)
      // 详情数据
      const detailItem = detailData.data[0]
      console.log('store.collectArr', store.collectArr)
      // 让收藏页面数据的状态和详情页面数据状态保持一致
      store.collectArr.forEach((item) => {
        if (item.id === detailItem.id) {
          detailItem.collect = item.collect
        }
      })
      // 详情数据赋值
      setDetailItem(detailItem)
    }
    fetchDetail()
  }, [])

  useEffect(() => {
    // console.log('---------------------------------------------------------', detailItem)
    // 更新结束之后，传递给redux
    if (flag) {
      dispatch(set_collect_arr(detailItem))
    }
  }, [detailItem])

  return (
    <div>
      <Button
        onClick={() => {
          navigate(-1)
        }}
      >
        返回上一页
      </Button>
      <hr />
      {/* {detailItem.map((item) => { */}
      {/* return ( */}
      <Fragment>
        <div style={{ width: 150, height: 150 }}>
          <ImageView src={detailItem.img}></ImageView>
        </div>
        <h1>{detailItem.title}</h1>
        <span
          onClick={() => {
            setFlag(true)
            // 更新详情收藏效果
            setDetailItem({ ...detailItem, collect: !detailItem.collect })
          }}
          className={detailItem.collect ? 'collect-btn active' : 'collect-btn'}
        >
          {detailItem.collect}
          收藏
        </span>
      </Fragment>
      {/* ) */}
      {/* })} */}
    </div>
  )
}

export default Detail
